// 删除用户API实现
// 添加到 backend/example-api.js

// 删除用户（管理员功能）
app.post('/api/admin/delete-user', async (req, res) => {
    try {
        const { openid, adminKey } = req.body;

        // 验证管理员密钥
        if (adminKey !== process.env.ADMIN_KEY) {
            return res.json({
                code: 1,
                message: '无权限'
            });
        }

        // 验证参数
        if (!openid) {
            return res.json({
                code: 1,
                message: '缺少参数'
            });
        }

        // 开始事务
        await connection.beginTransaction();

        try {
            // 1. 删除用户的报修工单
            await connection.query(
                'DELETE FROM repair_orders WHERE openid = ?',
                [openid]
            );

            // 2. 删除用户的借用记录
            await connection.query(
                'DELETE FROM asset_loans WHERE openid = ?',
                [openid]
            );

            // 3. 删除用户的订阅消息记录（如果有）
            await connection.query(
                'DELETE FROM subscription_messages WHERE openid = ?',
                [openid]
            );

            // 4. 删除用户本身
            const [result] = await connection.query(
                'DELETE FROM users WHERE openid = ?',
                [openid]
            );

            if (result.affectedRows === 0) {
                await connection.rollback();
                return res.json({
                    code: 1,
                    message: '用户不存在'
                });
            }

            // 提交事务
            await connection.commit();

            res.json({
                code: 0,
                message: '用户删除成功',
                data: {
                    deletedOpenid: openid
                }
            });

        } catch (error) {
            // 回滚事务
            await connection.rollback();
            throw error;
        }

    } catch (error) {
        console.error('删除用户失败:', error);
        res.json({
            code: 1,
            message: '删除失败: ' + error.message
        });
    }
});

// 批量删除用户（可选功能，用于管理员批量操作）
app.post('/api/admin/delete-users-batch', async (req, res) => {
    try {
        const { openids, adminKey } = req.body;

        // 验证管理员密钥
        if (adminKey !== process.env.ADMIN_KEY) {
            return res.json({
                code: 1,
                message: '无权限'
            });
        }

        // 验证参数
        if (!openids || !Array.isArray(openids) || openids.length === 0) {
            return res.json({
                code: 1,
                message: '参数错误'
            });
        }

        // 开始事务
        await connection.beginTransaction();

        try {
            let deletedCount = 0;

            for (const openid of openids) {
                // 删除相关数据
                await connection.query(
                    'DELETE FROM repair_orders WHERE openid = ?',
                    [openid]
                );
                await connection.query(
                    'DELETE FROM asset_loans WHERE openid = ?',
                    [openid]
                );
                await connection.query(
                    'DELETE FROM subscription_messages WHERE openid = ?',
                    [openid]
                );

                // 删除用户
                const [result] = await connection.query(
                    'DELETE FROM users WHERE openid = ?',
                    [openid]
                );

                if (result.affectedRows > 0) {
                    deletedCount++;
                }
            }

            // 提交事务
            await connection.commit();

            res.json({
                code: 0,
                message: `成功删除 ${deletedCount} 个用户`,
                data: {
                    deletedCount,
                    totalRequested: openids.length
                }
            });

        } catch (error) {
            // 回滚事务
            await connection.rollback();
            throw error;
        }

    } catch (error) {
        console.error('批量删除用户失败:', error);
        res.json({
            code: 1,
            message: '删除失败: ' + error.message
        });
    }
});
